#include "Grid.h"
#include "SceneMgr.h"
#include "Character/Creature.h"

Grid::Grid()
	: size(0), m_gridPos({0,0})
{
}

Grid::~Grid()
{
	size = 0;
}

void Grid::RemoveCid(CharIDType cid)
{
	for(auto pNode = m_cidLst.Head(); pNode != nullptr; pNode = m_cidLst.Next(pNode))
	{
		Creature* pCreature = (Creature*)pNode->GetHost();
		if (nullptr != pCreature)
		{
			if (pCreature->GetCid() == cid)
			{
				m_cidLst.Delete(pNode);
				//delete pCid;
				delete pNode;
				break;
			}
		}
		//CharIDType* pCid = (CharIDType*)pNode->GetHost();
	/*	if (*pCid == cid)
		{
			m_cidLst.Delete(pNode);
			delete pCid;
			delete pNode;
			break;
		}*/
	}
}

void Grid::RemoveCreature(Creature* pCreature)
{
	if (pCreature)
	{
		if (pCreature->GetGrid() == this && pCreature->GetGridNode() != nullptr)
		{
			DoubleNode* pDelNode = pCreature->GetGridNode();
			m_cidLst.Delete(pCreature->GetGridNode());
			//delete (CharIDType*)pDelNode->GetHost();
			delete pDelNode;
			size--;
			pCreature->SetGrid(nullptr);
			pCreature->SetGridNode(nullptr);
		}
		else
		{
			LogAlwaysFmtPrint("pCreature->GetGrid() != thisi, Grid::RemoveCreature failed, cid=%ld", pCreature->GetCid());
		}
	}
}

void Grid::UnInit()
{
	for(auto pNode = m_cidLst.Head(); pNode != nullptr; )
	{
		auto pDelNode = pNode;
		pNode = m_cidLst.Next(pNode);

		//delete (Creature*)pDelNode->GetHost();
		delete pDelNode;
	}
	m_cidLst.Clear();
	size = 0;
}

void Grid::AddCreature(Creature* pCreature)
{
	if (pCreature)
	{
		if (pCreature->GetGridNode() == nullptr && pCreature->GetGrid() == nullptr)
		{
			DoubleNode* pNode = new DoubleNode();
			//CharIDType* pCid = new CharIDType;
			//*pCid = pCreature->GetCid();
			//pNode->SetHost((void*)pCid);
			pNode->SetHost(pCreature);
			pCreature->SetGrid(this);
			pCreature->SetGridNode(pNode);

			m_cidLst.InsertTail(pNode);
			size++;
		}
		else
		{
			LogAlwaysFmtPrint("pCreature->GetGridNode() != nullptr || pCreature->GetGrid() != nullptr, cid=%ld", pCreature->GetCid());
		}
	}
}

void Grid::RemoveNode(DoubleNode* pNode)
{
	if (nullptr != pNode)
	{
		m_cidLst.Delete(pNode);
	}
}


